import Vue from 'vue'
import Vuex from 'vuex'
import qs from 'qs'

Vue.use(Vuex)

export default new Vuex.Store({
    //保存共享数据，该bookInfo.js服务于 book相关视图
    state: {
        total: null, //总记录数
        routeUrl: { //常量，保存相关url
            bookList: '/book/list',
            addBook: '/book/addBook',
            updateBook: '/book/updateBook',
        },
        //后端接口，全为post，详情看我的项目后端项目swagger
        backEndUrl: {
            deleteUrl: '/book/deleteBook',
            addUrl: '/book/addBook',
            queryBooksUrl: '/book/queryBooksByLimit',
            queryByIdUrl: '/book/queryBookById',
            updateUrl: '/book/updateBook',
            checkExistUrl: '/book/checkExist',
            queryAllBooksUrl: '/book/queryAllBooks',
        },
        bookInfo: { //book实体类模型
            id: null,
            name: null,
            author: null,
            count: null,
            category: null
        },
        bookFormRules: { //增加、修改图书时相关表单字段的规则
            name: [
                {required: true, message: '请输入书名', trigger: 'blur'},
                {pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/, message: "请勿输入特殊字符", trigger: "blur"},
                {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
            ],
            author: [
                {required: true, message: '请输入作者名字', trigger: 'blur'},
                {pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/, message: "请勿输入特殊字符", trigger: "blur"},
                {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
            ],
            category: [
                {required: true, message: '请选择图书分类', trigger: 'change'}
            ],
        },
        books: null, //后端返回的书籍列表
    },
    mutations: { //一般用于set,  通过store.commit('方法‘,参数)调用
        setBooks(state, books) {
            state.books = books;
        }, setTotal(state, total) {
            state.total = total;
        }
    },
    actions: { //异步处理方法，调用时只有then中的语句会等待其完成才执行
        //store.dispatch('方法',参数).then(rs=>{ ... });
        //其中store是固有参数，form才是传来的参数(json数据)
        queryBooks(store, form) {  /*查询书籍列表*/
            //反正别管promise是啥，只要知道这么写就行， resolve(data),即返回给调用者的数据
            //controller后台接受的是单独参数，需要qs.stringify({...}), qs需要import(axios自带)
            return new Promise((resolve) => {
                axios.post(store.state.backEndUrl.queryBooksUrl, qs.stringify({
                    name: form.searchContent,
                    category: form.category,
                    pageNo: form.pageNo,
                    pageSize: form.pageSize
                })).then(resp => {
                    //controller返回的不是string，不用eval倒是令我方便了许多
                    if (resp) { //防止报错
                        store.commit('setBooks', resp.data.list); //设置，store即本store
                        store.commit('setTotal', resp.data.total);
                    }
                    resolve(resp.data.list); //似乎不resolve就不能再dispatch时 then
                });
            });
        },
        deleteBookById(store, bookId) {
            return new Promise((resolve) => {
                axios.post(store.state.backEndUrl.deleteUrl, qs.stringify({id: bookId})).then(resp => {
                    resolve(resp);
                }).catch(() => {
                    resolve(false);
                });
            });
        },
        queryBookById(store, bookId) {
            return new Promise((resolve) => {
                axios.post(store.state.backEndUrl.queryByIdUrl, qs.stringify({
                    id: bookId
                })).then(function (resp) {
                    resolve(resp.data);
                }).catch(() => {
                    resolve(null);
                });
            });
        },
        addBook(store, book) {
            /*这个controller后端接受的是 Book对象，要写上header, 并且不用qs, 但好像可以设置默认header，到时候所有请求都携带*/
            return new Promise(resolve => {
                axios.post(store.state.backEndUrl.addUrl, book, {
                    headers: {
                        'content-type': 'application/json' //@requestBody,不能用qs
                    }
                }).then(resp => {
                    resolve(resp.data);
                }).catch(() => resolve(false));
            });
        },
        updateBook(store, book) {
            return new Promise(resolve => {
                axios.post(store.state.backEndUrl.updateUrl, book, {
                    headers: {
                        'content-type': 'application/json' //@requestBody,不能用qs
                    }
                }).then(resp => {
                    resolve(resp.data);
                }).catch(() => resolve(false));
            });
        },
        checkBookExist(store, book) {
            return new Promise(resolve => {
                axios.post(store.state.backEndUrl.checkExistUrl, qs.stringify({
                    name: book.name,
                    author: book.author
                })).then(resp => {
                    resolve(resp.data);
                }).catch(() => resolve(false));
            });
        }, queryAllBooks(store, form) {
            return new Promise((resolve) => {
                axios.post(store.state.backEndUrl.queryAllBooksUrl, qs.stringify({
                    name: form.searchContent,
                    category: form.category,
                })).then(resp => {
                    resolve(resp.data);
                });
            });
        },
    },
    modules: {},
    getters: { //get方法
        getBooks(state) { //store.getters.getBooks
            return state.books;
        },
        getTotal(state) {
            return state.total;
        },
        getBookForm(state) {
            return state.bookInfo;
        },
        getFormRules(state) {
            return state.bookFormRules;
        }
    }
})
